<?php

namespace app\api\controller;
use app\common\model\Enum;
use app\api\model\HttpMachine;
use app\api\model\User as UserModel;
use think\Db;
use think\facade\Cache;
use think\facade\Validate;



/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
		$model = new UserModel;
		$post = $this->request->post();
        $user = $model->login($post);
        if($user == null){
            return $this->renderError("系统开小差了,请再次点击!");
        }
        $token = $model->getToken();
        return $this->renderSuccess(compact('user', 'token'));
    }
	
	public function login_old()
    {
		$model = new UserModel;
		$post = $this->request->post();
        $user = $model->login_old($post);
        $token = $model->getToken();
        return $this->renderSuccess($user);
    }

    public function begin_transfer()
    {
        return $this->renderSuccess(1);
    }

 
    
    public function mybalance()
    {
        $model = new UserModel;
		$post = $this->request->post();
		$user =  $model->getUserId($post["uid"]);
        return $this->renderSuccess(compact('user'));
    }

    public function GetChargeListByUid()
    {
        
        $post = $this->request->post();
        $pageIndex = $post['pageIndex'];
        $pageSize = $post['pageSize'];
        $uid=$post["uid"];
        $map=[
            ['user_id', '=', $uid],
            ['pay_status', '=', Enum::PAY_SUCESS]
        ];
        $list=Db::table('charge')->where($map)->order('create_at', 'desc')->limit($pageSize)->page($pageIndex)->select();
        foreach ($list as &$row){
            $tname = array_search($row["type"],Enum::b_type_array);
            if(empty($tname)){
                $tname="";
            }
            $row["tname"] =$tname;
            $row["gift"] = $row["gift"]/100;
            $row["czamount"] =$row["czamount"]/100;
        }
        return $this->renderSuccess(compact('list'));
    }

    public function myOrderList()
    {
        
        $post = $this->request->post();
        $pageIndex = $post['pageIndex'];
        $pageSize = $post['pageSize'];
        $uid=$post["uid"];
        $map=[
            ['user_id', '=', $uid],
            ['pay_status', '=', Enum::PAY_SUCESS]
        ];
        $list=Db::table('order')->where($map)->order('create_at', 'desc')->limit($pageSize)->page($pageIndex)->select();
        foreach($list as &$value){ 
            $value['wash_type']=Enum::TransWashType($value['wash_type']);
        } 
        return $this->renderSuccess(compact('list'));
    }

    public function daybook()
    {
        $post = $this->request->post();
        $pageIndex = $post['pageIndex'];
        $pageSize = $post['pageSize'];
        $uid=$post["uid"];
        $map=[
            ['user_id', '=', $uid]
        ];
        $list=Db::table('daybook')->where($map)->order('id', 'desc')->limit($pageSize)->page($pageIndex)->select();
        foreach($list as &$value){ 
            $value['type']=array_search($value["b_type"],Enum::b_type_array);
        } 
        return $this->renderSuccess(compact('list'));
    }

    public function addFeedBack()
    {
        $post = $this->request->post();
        $data =array();
        $data['machine_no'] = $post['machineNo'];
        $data['report_desc'] = $post['desc'];
        $data['report_time'] = date('Y-m-d H:i:s',time());
        $data['user_id'] = $post["uid"];
        $id=Db::table('feed_back')->strict(false)->insertGetId($data);
        return $this->renderSuccess(1);
    }


    public function chargeList()
    {
        
        $post = $this->request->post();
        $map=[
        ];
        $list=Db::table('recharge_config')->where($map)->select();
        return $this->renderSuccess(compact('list'));
    }

    
    
    public function myCardList()
    {
        
        $post = $this->request->post();
        // $pageIndex = $post['pageIndex'];
        // $pageSize = $post['pageSize'];
        $uid=$post["uid"];
        $map=[
            ['user_id', '=', $uid],
            ['status', '=', Enum::BindCard_SUCESS]
        ];
        $list=Db::table('bindcard')->where($map)->select();
        return $this->renderSuccess(compact('list'));
    }


    public function BindCard()
    {
        
        $post = $this->request->post();
        $uid=$post["uid"];
        $cardNo=$post["cardNo"];
 
        $openid=$post["openid"];
        $unionid=$post["unionid"];
       
        if(!Validate::must($cardNo)){
            return $this->renderError("卡号不能为空",true);
        }

        $card = Db::table('cart')->where("cart_no",$cardNo)->find();
        if(!$card){
            return $this->renderError("卡号不存在，请检查",true);
        }

        $CardGift = Db::table('card_gift')->where("id",1)->find();
        if(!$CardGift){
            return $this->renderError("卡赠送设置有误，请联系客服",true);
        }

        $map=[
            ['user_id', '=', $uid],
            ['status', '=', Enum::BindCard_SUCESS]
        ];
        $count = Db::table('bindcard')->where($map)->count('id');
        if($count > (int)$CardGift['max_count']){
            return $this->renderError("绑卡数量超过限制",true);
        }

        $model = new UserModel;
        $user =  $model->getUserId($uid);
        if(!$user){
            return $this->renderError("用户不存在",true);
        }
        
        $insert=0;//新增绑定记录
        $zs=0;//新增赠送

        $map=[
            ['card_no', '=', $cardNo]
        ];
        $BindCard = Db::table('bindcard')->where($map)->find();
        if(!$BindCard){
            $insert=1;
            $zs=1;
        }else{
            $map=[
                ['Status', '=', Enum::BindCard_SUCESS],
                ['card_no', '=', $cardNo]
            ];
            $BindCard = Db::table('bindcard')->where($map)->find();
            if(!$BindCard){
                //二次使用的卡,只能绑定,不会赠送
                $insert=1;
            }else{
                return $this->renderError("该卡已被绑定,不能重复绑定!",true);
            }
        }

        $time = date('Y-m-d H:i:s',time());
        
        if($zs==1){
            $amount = (int)$CardGift['gift_amount'];
            $no_cz = Enum::orderNo(Enum::order_type_kkcz);
            $data_cz=[
                'user_id' => $uid,
                'open_id' => $openid,
                'union_id' => $unionid,
                'type' => Enum::b_type_kkcz,
                'trade_no' =>"",//记录订单订单的单号
                'card_no' => $cardNo,
                'order_no' => $no_cz,
                'apsid' => "",
                'pay_status' => Enum::PAY_SUCESS,
                'create_at' => $time,
                'update_at' => $time,
                'czamount' => $amount,
                'amount' =>$amount,
                'gift' => 0
            ];

            $book_cz=[
                'user_id' => $user['id'],
                'b_type' => Enum::b_type_kkcz,
                'b_id' => 0,
                'b_no' => $no_cz,
                'create_at' => $time,
                'old_amount' =>$user['amount'],
                'var_amount' =>$amount ,
                'amount' => $user['amount'] + $amount
            ];
        }
       
        
        $id=0;

        Db::startTrans();
        try {
            if($insert==1){
                $data =array();
                $data['user_id'] = $uid;
                $data['apsid'] = $user['apsid'];
                $data['card_no'] = $cardNo;
                $data['Status'] = Enum::BindCard_SUCESS;
                $data['create_at'] =$time;
                $data['update_at'] = $time;
                $id=Db::table('bindcard')->strict(false)->insertGetId($data);

                $sql="UPDATE `user` as a INNER JOIN  ( SELECT  GROUP_CONCAT(card_no SEPARATOR ',') as cards,user_id from (SELECT DISTINCT user_id,card_no from bindcard  where user_id = $uid ) a ) b  ON a.id = b.user_id SET a.cards = b.cards where a.id = $uid ";
                Db::execute($sql);
            }
    
            if($zs==1){
                //增加流水日志 业务类型, 业务id
                $data_cz['trade_no'] = $id;

                $charge_id=Db::table('charge')->insertGetId($data_cz);
                $book_cz['b_id'] = $charge_id;
                Db::table('daybook')->strict(false)->insert($book_cz);
    
                //这里还需要加一个的金额
                Db::table('user')->where('id',$uid)->setInc('amount',$amount);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->renderError('数据更新异常'.$e);
            $this->errLog('数据更新异常'.$e);
        }

        return $this->renderSuccess(1);
    }



    public function Unbind()
    {
        $post = $this->request->post();
        $uid=$post["uid"];
        $cardNo=$post["cardNo"];
        if(!Validate::must($cardNo)){
            return $this->renderError("卡号不能为空");
        }

        $model = new UserModel;
        $user =  $model->getUserId($post["uid"]);
        if(!$user){
            return $this->renderError("用户不存在");
        }

        $card = Db::table('cart')->where("cart_no",$cardNo)->find();
        if(!$card){
            return $this->renderError("卡号有误，请确认");
        }

        $map=[
            ['user_id', '=', $uid],
            ['status', '=', Enum::BindCard_SUCESS],
            ['card_no', '=', $cardNo]
        ];
        $BindCard = Db::table('bindcard')->where($map)->find();
        if(!$BindCard){
            return $this->renderError("卡不属于您,解绑失败!");
        }else{

            Db::table('bindcard')->where('id',$BindCard['id'])->update([ 'status'=> Enum::BindCard_FAILED, 'update_at' => date('Y-m-d H:i:s',time()) ]);

            $sql="UPDATE `user` as a INNER JOIN  ( SELECT  GROUP_CONCAT(card_no SEPARATOR ',') as cards,user_id from (SELECT DISTINCT user_id,card_no from bindcard  where user_id = $uid ) a ) b  ON a.id = b.user_id SET a.cards = b.cards where a.id = $uid ";
            Db::execute($sql);
        }

        return $this->renderSuccess(1);
    }


    public function QueryWashTypeAndPrice()
    {
        $post = $this->request->post();
        $uid=$post["uid"];
        $machineno= $post["machineno"];//"254819";//

        if(!Validate::must($machineno)){
            return $this->renderError("machineNo不能为空");
        }

        $map=[
            ['machine_no', '=', $machineno],
            ['is_deleted', '=', 0]
        ];
        $machine = Db::table('machine')->where($map)->find();
        if(!$machine){
            return $this->renderError("不存在的机器");
        }

        //

        $re = HttpMachine::GetMachineWorkStatus($machineno);
        if($re != "1"){
            return $this->renderError("请换一台机器使用");
        }

        $areaId = $machine["area_id"];
        $map=[
            ['area_id', '=', $areaId],
            ['is_deleted', '=', 0]
        ];
        $price = Db::table('price')->where($map)->select();

        foreach($price as $value){ 
            $data =array();
            $data['washtype'] =Enum::GetWashType((int)$value['wash_type']);
            $data['price'] = $value['wash_price'];
            $data['action'] = Enum::GetWashCommand((int)$value['wash_type']);
            $list[]=$data;
        } 


        return $this->renderSuccess($list);
    }

    public function transfer()
    {
        $post = $this->request->post();
        $oldunionid = $post["oldunionid"]; //"99f66fe77d1ff57b97e6908b63e77d76";
        //获取原用户信息
        $map=[
            ['union_id', '=', $oldunionid]
        ];
        $data_old = Db::connect('db_old')->table('user')->where($map)->find();
        if(empty($data_old)){
            return $this->renderError("未找到历史用户信息,请联系管理员");
        }

        // if($data_old["balance"]==1){
        //     return $this->renderSuccess(99);//已转移过了.不需要继续
        // }

        //找到对应的数据
        $map=[
            ['union_id', '=', $oldunionid]
        ];
        $user = Db::table('user')->where($map)->find();
        if(empty($user)){
            return $this->renderError("新系统用户信息无法匹配,请联系管理员");
        }

        //1 转移数据  2转移且金额同步了
        if($user["is_transfer"]==2){
            return $this->renderSuccess(99);//已转移过了.不需要继续
        }

        $map=[
            ['apsid', '=', $data_old["apsid"]]
        ];
        $bindcard_old=Db::connect('db_old')->table('bindcard')->field('user_id,card_no, create_at, update_at, apsid, status')->where($map)->select();

        foreach ($bindcard_old as &$row){
            $row["user_id"] =$user['id'];
        }
       
        $amount =  $data_old["amount"];

        //同步用户现在的金额
        if($amount >0)
        {
            $no = Enum::orderNo(Enum::order_type_cscz);
            $time =date('Y-m-d H:i:s',time());

            $data=[
                'user_id' => $user['id'],
                'open_id' => $user['open_id'],
                'union_id' => $user['union_id'],
                'type' => Enum::b_type_cscz,
                'trade_no' => "",
                'card_no' => "",
                'order_no' => $no,
                'apsid' => "",
                'pay_status' => Enum::PAY_SUCESS,
                'create_at' => $time,
                'update_at' => $time,
                'czamount' => $amount,
                'amount' => $amount,
                'gift' => 0
            ];

            //插入数据
            $n_amount = $user['amount'] + $amount;

            $book=[
                'user_id' => $user['id'],
                'b_type' => Enum::b_type_cscz,
                'b_id' => 0,
                'b_no' => $no,
                'create_at' => $time,
                'old_amount' =>$user['amount'],
                'var_amount' =>$amount ,
                'amount' => $n_amount
            ];
        }

        $bl=false;

        //处理绑卡的信息
        $uid =$user['id'];

        Db::startTrans();
        try 
        {
            if($amount >0)
            {
                $id=Db::table('charge')->insertGetId($data);
                $book['b_id'] =$id;
                Db::table('daybook')->strict(false)->insert($book);

                //用户的钱变化
                $c = Db::table('user')->where('id',$user['id'])->setInc('amount',$amount);
            }

            if(count($bindcard_old)>0){
                Db::table('bindcard')->strict(false)->insertAll($bindcard_old);
            }
            
            //字段变化
            Db::table('user')->where('id',$user['id'])->update([ 'is_transfer'=> 2,'transfer_at'=>$time]);
            
            if(count($bindcard_old)>0){
                $sql="UPDATE `user` as a INNER JOIN  ( SELECT  GROUP_CONCAT(card_no SEPARATOR ',') as cards,user_id from (SELECT DISTINCT user_id,card_no from bindcard  where user_id = $uid ) a ) b  ON a.id = b.user_id SET a.cards = b.cards where a.id = $uid ";
                Db::execute($sql);
            }

            $bl=true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->renderError('数据更新异常! - '.$e);
        }

        if($bl==true){
            Db::connect('db_old')->table('user')->where('union_id',$oldunionid)->update(['balance'=> 1]);
        }

        //用户的绑定卡信息已经同步过去了.把用户的余额全部转过去,做一次性充值.这样就断掉那边的金额了.
        return $this->renderSuccess(1); 
    }


    public function refund()
    {
        $post = $this->request->post();
        //1申请人, 申请金额.
        $uid = $post["uid"]; //"99f66fe77d1ff57b97e6908b63e77d76";
        $amount=$post["amount"];
        if(!Validate::must($amount)){
            return $this->renderError("金额不能为空");
        }

        
        if(!Validate::between($amount,"1,1000")){
            return $this->renderError("金额太大或太小");
        }


        $amount=$amount*100; //变为分

        $model = new UserModel;
        $user =  $model->getUserId($uid);
        if(!$user){
            return $this->renderError("用户不存在2");
        }

        if($user["amount"]<$amount){
            return $this->renderError("用户余额不足,不能发起对应金额的退款");
        }

       
        $time =date('Y-m-d H:i:s',time());
        $data=[
            'user_id' => $user['id'],
            'status' => 2,
            'create_at' => $time,
            'update_at' => $time,
            'amount' => $amount
        ];

        //插入数据
        $n_amount = $user['amount'] - $amount;
        $book=[
            'user_id' => $user['id'], //后补
            'b_type' => Enum::b_type_wxtk,
            'b_id' => 0,
            'b_no' => "",
            'create_at' => $time,
            'old_amount' =>$user['amount'],
            'var_amount' => $amount * -1 ,
            'amount' => $n_amount
        ];
        
        Db::startTrans();
        try {
            $id=Db::table('refund')->insertGetId($data);

            $book['b_id'] = $id;
            Db::table('daybook')->strict(false)->insert($book);

            //用户的钱变化
            $c = Db::table('user')->where('id',$user['id'])->setDec('amount',$amount);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->renderError('数据更新异常! - '.$e);
        }

        return $this->renderSuccess(1); 
    }

    public function myrefund()
    {
        $post = $this->request->post();
        $uid=$post["uid"];
        $map=[
            ['user_id', '=', $uid],
            ['status', '=', 2]
        ];
        $item=Db::table('refund')->where($map)->find();
        return $this->renderSuccess(compact('item'));
    }

    public function clearmachinelog()
    {
        //保留300条
        $list = Db::table('machine')->where('imei','<>','')->select();
        foreach($list as $value){ 
            $itemarr=Db::table('machine_log')->where('imei','=',$value['imei'])->order('id', 'desc')->limit(300,1)->select();
			
            if(!empty($itemarr) && count($itemarr) == 1){
				$item = $itemarr[0];
                $map=[
                    ['imei', '=', $item["imei"]],
                    ['id', '<', $item["id"]]
                ];
                Db::table('machine_log')->where($map)->delete();
            }
        } 
        //$re = Db::table('machine_log')->where('cretime','<',date("Y-m-d H:i:s",strtotime("-1 day")))->delete();
        return $this->renderSuccess(1);
    }

   

}

